//
//  EmoticonCollectionViewCell.swift
//  HotNews
//
//  Created by YYY on 2017/11/13.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

//定义协议
@objc protocol EmoticonCellDelegate: NSObjectProtocol
{
    //表格cell被选中的表情
    func emoticonCellDidSelectedEmoticon(cell: EmoticonCollectionViewCell, em: YYYEmoticonModel?)
}
class EmoticonCollectionViewCell: UICollectionViewCell
{
    //提示视图
    private lazy var tipView = EmoticonTipView()
    
    //定义代理
    weak var delegate: EmoticonCellDelegate?
    //表情
    var emoticons: [YYYEmoticonModel]?
    {
        didSet
        {
            for btn in contentView.subviews
            {
                btn.isHidden = true
            }
            //显示删除按钮
            contentView.subviews.last?.isHidden = false
            for (i, model) in (emoticons ?? []).enumerated()
            {
                let btn = contentView.subviews[i] as! UIButton
                //设置btn图片，如果image为nil，则清空图片，避免复用问题
                btn.setImage(model.image, for: .normal)
                //设置btn标题，如果emoji为nil，则清空标题，避免复用问题
                btn.setTitle(model.emoji, for: .normal)
                btn.isHidden = false
            }
        }
    }
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        
        //初始化控件
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加按钮的监听方法
    @objc private func selectedEmoticonButton(selectedButton: UIButton)
    {
        //取tag
        let tag = selectedButton.tag
        var em: YYYEmoticonModel?
        
        //tag值范围[0,20],20对应的是删除按钮
        if tag < (emoticons?.count ?? 0)
        {
            em = emoticons?[tag]
        }
        //如果em是nil，对应的是删除按钮
        delegate?.emoticonCellDidSelectedEmoticon(cell: self, em: em)
    }
    
    @objc private func longPressGesture(gesture: UILongPressGestureRecognizer)
    {
        let location = gesture.location(in: self)
        
        guard let currentButton = buttonWithLocation(location: location) else
        {
            tipView.isHidden = true
            return
        }
        switch gesture.state {
        case .began, .changed:
            //坐标系转换，将按钮在cell的中心位置，转换到window上
            let center = self.convert(currentButton.center, to: window)
            tipView.center = center
            //tipView.center.y = center.y - 70
            tipView.isHidden = false
            let count = emoticons?.count ?? 0
            if currentButton.tag < count
            {
                tipView.emoticonModel = emoticons?[currentButton.tag]
            }
        case .ended:
            tipView.isHidden = true
            //选中表情到文本视图
            selectedEmoticonButton(selectedButton: currentButton)
        case .failed, .cancelled:
            tipView.isHidden = true
        default:
            break
        }
    }
    
    //根据触摸位置，找出对应的表情按钮
    private func buttonWithLocation(location: CGPoint) -> UIButton?
    {
        for btn in (contentView.subviews as! [UIButton])
        {
            if btn.frame.contains(location) && !btn.isHidden && (btn != contentView.subviews.last)
            {
                return btn
            }
        }
        return nil
    }
    
    //将提示视图添加到UIWindow窗口上
    override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)
        guard let window = newWindow else
        {
            return
        }
        //隐藏提示视图
        tipView.isHidden = true
        window.addSubview(tipView)
    }
}

extension EmoticonCollectionViewCell
{
    //初始化控件
    func setupUI()
    {
        //行数
        let rowCount = 3
        //列数
        let colCount = 7
        
        //左间距
        let leftMargin: CGFloat = 8
        //底部间距
        let bottomMargin: CGFloat = 16
        
        //宽度
        let buttonWidth = (bounds.width - CGFloat(2) * leftMargin)/CGFloat(colCount)
        //高度
        let buttonHeight = (bounds.height - bottomMargin)/CGFloat(rowCount)
        
        //加载21个按钮
        for i in 0..<21
        {
            let btn = UIButton()
            let row = i / colCount
            let col = i % colCount
            let x: CGFloat = leftMargin + CGFloat(col) * buttonWidth
            let y: CGFloat = CGFloat(row) * buttonHeight
            btn.frame = CGRect(x: x, y: y, width: buttonWidth, height: buttonHeight)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
            //设置btn的tag值
            btn.tag = i
            //添加监听方法
            btn.addTarget(self, action: #selector(selectedEmoticonButton), for: .touchUpInside)
            contentView.addSubview(btn)
        }
        
        //取出删除按钮
        let removeBtn = contentView.subviews.last as! UIButton
        let image = UIImage(named: "compose_emotion_delete_highlighted", in: EmoticonManager.shared.bundle, compatibleWith: nil)
        removeBtn.setImage(image, for: .normal)
        //添加长按手势
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressGesture))
        //手势的最小时间间隔
        longPress.minimumPressDuration = 0.1
        addGestureRecognizer(longPress)
    }
}
